from appengine_django.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils.datetime_safe import date
from forms import HillForm
from google.appengine.api import users
from hocine_dourthe_skiing.forms import RunForm, LiftForm, UserForm, HillRunForm, \
    FeedbackForm
from hocine_dourthe_skiing.models import Hill, UserRight, Lift, Run, Feedback
import google.appengine.ext.db.djangoforms as forms
import time

def is_super_admin():
    if  users.get_current_user():
        return UserRight.all().filter("mail = ", users.get_current_user().email()).get().superadmin
    else:
        return False

def tryLog(request,page, form, form_name):
    user = users.get_current_user()
    if user:
        if form.is_valid(): 
            form.save()
            return HttpResponseRedirect("/")
        else:
            return render_to_response(page, RequestContext(request, {form_name:form, 'is_authenticated':True}))
    else:
        return HttpResponseRedirect(users.create_login_url(request.get_full_path()))

def index(request):
    hills = Hill.all().order("name")
    if users.get_current_user():
        is_authenticated = True
    else:
        is_authenticated = False
    return render_to_response("index.html", RequestContext(request, {'hills':hills, 'is_authenticated':is_authenticated}))
 
def createHill(request):
    if request.POST:
        return tryLog(request,"hill_form.html",HillForm(request.POST), 'hill_form')
    else:
        return tryLog(request,"hill_form.html",HillForm(), 'hill_form')
    
def createRun(request):
    if is_super_admin() :
        if request.POST:
            return tryLog(request,"run_form.html",RunForm(request.POST), 'run_form')
        else:
            return tryLog(request,"run_form.html",RunForm(), 'run_form')
    else:
        if  users.get_current_user():
            run = Run(name="name", hill=UserRight.all().filter("mail = ", users.get_current_user().email()).get().hill)
            if request.POST:
                return tryLog(request,"run_form.html",HillRunForm(request.POST, instance=run), 'run_form')
            else:
                return tryLog(request,"run_form.html",HillRunForm(), 'run_form')
        else:
            return tryLog(request,"run_form.html",HillRunForm(), 'run_form')

def createLift(request):
    if is_super_admin() :
        if request.POST:
            return tryLog(request,"lift_form.html",LiftForm(request.POST), 'lift_form')
        else:
            return tryLog(request,"lift_form.html",LiftForm(), 'lift_form')
    else:
        lift_form = LiftForm(request.POST)
        if request.POST:
            return tryLog(request,"lift_form.html",lift_form, 'lift_form')
        else:
            return tryLog(request,"lift_form.html",LiftForm(), 'lift_form')
    

def userRight(request):
    if request.POST:
        return tryLog(request,"userright_form.html",UserForm(request.POST), 'userright_form')
    else:
        return tryLog(request,"userright_form.html",UserForm(), 'userright_form')
    
def editHill(request, hill_id):
    hill = Hill.get_by_id(int(hill_id))
    if request.POST:
        return tryLog(request,"hill_form.html",HillForm(request.POST, instance=hill), 'hill_form')
    else:
        return tryLog(request,"hill_form.html",HillForm(None, instance=hill), 'hill_form')
    
def editRun(request, run_id):
    run = Run.get_by_id(int(run_id))
    if request.POST:
        return tryLog(request,"run_form.html",RunForm(request.POST, instance=run), 'run_form')
    else:
        return tryLog(request,"run_form.html",RunForm(None, instance=run), 'run_form')
    
def editLift(request, lift_id):
    lift = Run.get_by_id(int(lift_id))
    if request.POST:
        return tryLog(request,"lift_form.html",LiftForm(request.POST, instance=lift), 'lift_form')
    else:
        return tryLog(request,"lift_form.html",LiftForm(None, instance=lift), 'lift_form')
    
def viewHill(request, hill_id):
    hill = Hill.get_by_id(int(hill_id))
    runs = Run.all().filter("hill", hill)
    
    open_run = Run.all().filter("hill", hill).filter("state", True).count(None)
    
    green = Run.all().filter("hill", hill).filter("typeRunning", 1).count(None)
    open_green = Run.all().filter("hill", hill).filter("typeRunning", 1).filter("state", True).count(None)
    
    blue = Run.all().filter("hill", hill).filter("typeRunning", 2).count(None)
    open_blue = Run.all().filter("hill", hill).filter("typeRunning", 2).filter("state", True).count(None)
    
    red = Run.all().filter("hill", hill).filter("typeRunning", 3).count(None)
    open_red = Run.all().filter("hill", hill).filter("typeRunning", 3).filter("state", True).count(None)
    
    black = Run.all().filter("hill", hill).filter("typeRunning", 4).count(None)
    open_black = Run.all().filter("hill", hill).filter("typeRunning", 4).filter("state", True).count(None)
    
    if users.get_current_user():
        is_authenticated = True
    else:
        is_authenticated = False
    return render_to_response("hill.html", RequestContext(request, {'hill':hill, 
                                                                    'runs':runs, 'open_run':open_run,
                                                                    'green':green, 'open_green':open_green,
                                                                    'blue':blue, 'open_blue':open_blue,
                                                                    'red':red, 'open_red':open_red,
                                                                    'black':black, 'open_black':open_black, 'is_authenticated':is_authenticated}))
        
def viewRun(request, run_id):
    erun = Run.get_by_id(int(run_id))
    
    feedback = Feedback(run=erun)
    if request.POST:
        feedback_form = FeedbackForm(request.POST, instance=feedback)
    else:
        feedback_form = FeedbackForm(None, instance=feedback)
    
    if request.POST and feedback_form.is_valid(): 
        feedback_form.save()

    #print feedback_form.fields['grade']
    lifts = Lift.all().filter("run", erun)
    open_lifts = Lift.all().filter("run", erun).filter("state", True).count(None)
    #print lifts
    feedbacks = Feedback.all().filter("run", erun).order("-date")
    grade = 0    
    if(feedbacks.count(None) != 0):  
        for feedback in feedbacks:
            grade += feedback.grade  
        grade = float(grade) / float(feedbacks.count(None))

    if users.get_current_user():
        is_authenticated = True
    else:
        is_authenticated = False
        
    return render_to_response("run.html", RequestContext(request, {'run':erun, 'lifts':lifts, 'open_lifts':open_lifts, 
                                                                       'feedbacks':feedbacks, 'feedback_form' : feedback_form,
                                                                       'grade':grade,'is_authenticated':is_authenticated}))
def cron_feedback(request):
    feedback = Feedback.all().filter("date < ", date.fromtimestamp(time.time() - 72 * 60 * 60))
    for feed in feedback:
        feed.delete()
    
    return render_to_response('index.html')
